from sqlalchemy import select
from database.engine import get_session_factory
from database.models.product import Product


class SynOrmProductQueries:
    @staticmethod
    def get_products():
        with get_session_factory()() as session:
            query = (
                select(Product)
            )
            
            result_iterator = session.execute(query)
            result = result_iterator.scalars().all()
            
            return result
        
        
    @staticmethod
    def get_product_by_product_name_and_username(product_name, username):
        with get_session_factory()() as session:
            query = (
                select(Product)
                .where(Product.name == product_name)
                .where(Product.username == username)
            )
            
            result_iterator = session.execute(query)
            result = result_iterator.scalars().one_or_none()
            
            return result
        
        
    @staticmethod
    def insert_product(**kwargs):
        with get_session_factory()() as session:
            session.add(Product(**kwargs))
            session.commit()
            
            
    @staticmethod
    def update_product(**kwargs):
        with get_session_factory()() as session:
            product = session.get(
                Product, 
                {
                    "name": kwargs["name"],  
                    "username": kwargs["username"],
                }
            )
            for key, value in kwargs.items():
                if key not in ["name", "username"]:
                    setattr(product, key, value)
            session.commit()
            
            
    @staticmethod
    def delete_product(name: str, username: str):
        with get_session_factory()() as session:
            product = session.get(Product, {"name": name, "username": username})
            session.delete(product)
            session.commit()
            